package gitea_sdk

import (
	"devops/pkg/git/git_model"

	"code.gitea.io/sdk/gitea"
)

//const Token = "0f7189624bc05cf5de59b0fdbbadd59e5567c713"

type giteaClient struct {
	g *gitea.Client
}

func NewGiteaClient(token string, url string) *giteaClient {
	client, err := gitea.NewClient(url, gitea.SetToken(token))
	if err != nil {
		return nil
	}
	_, _, err = client.GetMyUserInfo()
	if err != nil {
		return nil
	}
	return &giteaClient{g: client}
}

func (tea *giteaClient) GetRepos() ([]git_model.Repo, error) {
	teaRepos, _, err := tea.g.SearchRepos(gitea.SearchRepoOptions{})
	if err != nil {
		return nil, err
	}
	repos := make([]git_model.Repo, 0, len(teaRepos))
	for _, teaRepo := range teaRepos {
		repo := git_model.Repo{
			FullName: teaRepo.FullName,
			Name:     teaRepo.Name,
			Owner: git_model.User{
				Login:     teaRepo.Owner.UserName,
				AvatarUrl: teaRepo.Owner.AvatarURL,
				HtmlUrl:   "",
			},
			Path:        teaRepo.Name,
			Description: teaRepo.Description,
			HtmlUrl:     teaRepo.HTMLURL,
			CloneUrl:    teaRepo.CloneURL,
		}
		repos = append(repos, repo)
	}
	return repos, nil
}

func (tea *giteaClient) GetBranches(owner string, repo string) []git_model.Branch {
	giteaBranches, _, err := tea.g.ListRepoBranches(owner, repo, gitea.ListRepoBranchesOptions{})
	if err != nil {
		return nil
	}
	branches := make([]git_model.Branch, 0, len(giteaBranches))
	for _, giteaBranch := range giteaBranches {

		branches = append(branches, git_model.Branch{Name: giteaBranch.Name, CommittedDate: git_model.CommittedDate(&giteaBranch.Commit.Timestamp)})
	}
	return branches
}

func (tea *giteaClient) GetRepoCommit(owner string, repo string, branch string) {
	//comments, _, err := tea.g.ListRepoCommits(owner, repo, gitea.ListCommitOptions{SHA: branch})
	//if err != nil {
	//	return nil
	//}
}
